﻿#region 命名空间

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using WinnerCMS.Common;
using WinnerCMS.PlugIn.OpenAPI.Config;

#endregion

namespace WinnerCMS.PlugIn.OpenAPI.Passport
{
    /// <summary>
    /// 提交整合要求类
    /// </summary>
    public class Client
    {
        public string Status = string.Empty;


        public List<string> ErrList = new List<string>();
        private MemberInfo _minfo;
        private HttpContext _context;
        private readonly APIConfig _config;

        public Client(HttpContext context)
        {
            this._context = context;
            this._config = APIConfigManage.GetConfig();
        }

        /// <summary>
        /// 连接各个api站点
        /// </summary>
        /// <param name="action"></param>
        /// <param name="model"></param>
        public void ConnectionAPIs(string action, MemberInfo model)
        {
            if (this._config.DPOEnable == false)
                return;
            if (this._config.NodeList == null)
                return;
            foreach (Node app in this._config.NodeList)
            {
                if (app.Url.StartsWith("http://", StringComparison.CurrentCultureIgnoreCase) == false)
                {
                    continue;
                }

                this._minfo = model;
                Post(app.Url, action);
            }
        }


        private void Post(string url, string action)
        {
            string authToken = Hash.Md5(string.Concat(this._minfo.UserName, this._config.AppKey));

            this._minfo.Appid = this._config.AppID;
            this._minfo.Action = action;
            this._minfo.Syskey = authToken;

            string resultPost;
            try
            {
                CookieContainer cookieContainer = new CookieContainer();
                HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);

                request.Method = "POST";
                request.ContentType = "text/xml";
                request.CookieContainer = cookieContainer;
                request.KeepAlive = true;
                request.ProtocolVersion = HttpVersion.Version11;
                request.Credentials = CredentialCache.DefaultCredentials;
                request.CookieContainer = cookieContainer;
                request.Accept = "*/*";
                request.Headers.Add("Accept-Encoding", "gzip, deflate");
                request.Headers.Add("Accept-Language", "zh-cn");
                request.Headers.Add("UA-CPU", "x86");
                request.UserAgent =
                    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET CLR 3.0.30618; MAXTHON 2.0)";

                byte[] buffer1 = SerializableHelper.SerializeToBytes(this._minfo);
                request.ContentLength = buffer1.Length;
                Stream stream1 = request.GetRequestStream();
                stream1.Write(buffer1, 0, buffer1.Length);
                stream1.Close();


                HttpWebResponse res = (HttpWebResponse) request.GetResponse();

                if (!string.IsNullOrEmpty(res.Headers[HttpResponseHeader.SetCookie]))
                {
                    string s = res.Headers[HttpResponseHeader.SetCookie];
                    MatchCollection M = new Regex("(.*?)=(.*?)path=(.*?),", RegexOptions.IgnoreCase).Matches(s + ",");

                    foreach (Match m in M)
                    {
                        HttpCookie hc = PassportHelper.GetCookieFromString(m.Groups[0].Value.TrimEnd(','));
                        if (hc != null)
                            HttpContext.Current.Response.Cookies.Add(hc);
                    }
                }

                Stream stream2 = res.GetResponseStream();
                StreamReader reader1 = new StreamReader(stream2, Encoding.UTF8);
                resultPost = reader1.ReadToEnd();

                reader1.Close();
            }
            catch (Exception ex)
            {
                AddMsg(ex.Message);
                return;
            }

            try
            {
                MemberInfo mi = SerializableHelper.DeSerialize<MemberInfo>(resultPost, DataFormart.Xml);
                if (mi.Status == "0")
                {
                    AddMsg(mi.Message);
                }
            }
            catch
            {
                AddMsg("解析返回信息出错，请重试！");
            }
        }

        /// <summary>
        /// 错误处理函数
        /// </summary>
        /// <param name="message"></param>
        private void AddMsg(string message)
        {
            this.ErrList.Add(string.Format("{0}提示您：{1}", this._minfo.Appid, message));
        }
    }
}